package com.gome.ss.webserver.servlet.api;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.gome.ss.core.plugin.PluginManager;
import com.gome.ss.core.schedule.ScheduleManager;
import com.gome.ss.schedule.model.PluginModel;

public class GetPluginInfoServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String pluginName = req.getParameter("pluginName");
		
		resp.setContentType("text/html;charset=gbk");
		req.setCharacterEncoding("gbk");
		
		JSONArray pluginArr = new JSONArray();
		
		if (pluginName == null || pluginName.isEmpty()) {

			Set<String> pnames = PluginManager.getInstance().getPluginNameSet();
			
			for ( String name : pnames ) {
				JSONObject result = new JSONObject();
				List<PluginModel> pms = PluginManager.getInstance().getPluginModelByName(name);
				
				for (PluginModel pm : pms) {
					result.put("name", name);
					result.append("plugins", pm.getJSONObject());
				}
				pluginArr.put(result);
			}
		} else {
			JSONObject result = new JSONObject();

			List<PluginModel> pms = PluginManager.getInstance().getPluginModelByName(pluginName);
			for (PluginModel pm : pms) {
				result.put("name", pluginName);
				result.put("fileName", PluginManager.getInstance().getPluginFileName(pluginName));
				result.put("isLocalPlugin", PluginManager.getInstance().isLocalPlugin(pluginName));
				result.append("plugins", pm.getJSONObject());
			}
			pluginArr.put(result);
		}
		
		resp.getWriter().print(pluginArr.toString());
		resp.getWriter().close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req, resp);
	}

}
